#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>

#include<fcntl.h>
#define BUFFER_SIZE 1
extern int errno;
int main(int argc, char* argv[]){
    //判断参数是否符合标准
    if(argc!=3){
        printf("mycp requires 2 arguments, but got %d.\n", argc-1);
        return -1;
    }
    char* originFile = argv[1];
    char* targetFile = argv[2];
    int fr = open(originFile,O_RDONLY);
    int fw = open(targetFile,O_WRONLY);
    //如果源文件不存在或是文件夹，报错
    if(fr == -1){
        perror(originFile);
        return 0;
    }
    printf("origin:%s\n",originFile);
    //如果目标文件存在，给出提示
    if(fw != -1){
        printf("%s already exists. Enter 1 to overwrite or enter 2 to append.\n",targetFile);
        close(fw);
        int flag = getchar();
        if(flag == '1'){
            fw = open(targetFile,O_WRONLY|O_TRUNC);
        }else if(flag == '2'){
            fw = open(targetFile,O_WRONLY|O_APPEND);
        }else{
            printf("Got wrong input.\n");
        }
    }else{
        struct stat st;
        stat(targetFile,&st);
        if(S_ISDIR(st.st_mode)){//存在但是dir
            char* ofname;
            if(ofname=strrchr(originFile,'/')){
                strcat(targetFile,ofname);
            }else{
                strcat(targetFile,"/");
                strcat(targetFile,originFile);
            }
        }
        printf("target:%s\n",targetFile);
        //不是dir且不存在
        fw = open(targetFile,O_CREAT|O_EXCL|O_WRONLY,S_IRUSR|S_IWUSR);
        if(fw==-1){
            printf("%s:target directory doesn't exits.\n",targetFile);
        }
    }
    char buf[BUFFER_SIZE]={'\0'};
    int readLen=read(fr,buf,BUFFER_SIZE);
    int writeLen=write(fw,buf,sizeof(buf));
    while(readLen != 0){
        readLen=read(fr,buf,BUFFER_SIZE);
        writeLen=write(fw,buf,sizeof(buf));
    }
    close(fr);
    close(fw);
}